package com.culture.bootdemo.dao;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.culture.bootdemo.model.dto.CommonDTO;
import com.culture.bootdemo.model.req.UserReq;
import com.culture.bootdemo.po.Answer;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.type.JdbcType;

import java.util.List;

/**
 * @author ：wen
 * @date ：Created in 2019/8/5 17:52
 * @description：:
 */
@Mapper
public interface AnswerMapper extends BaseMapper<Answer> {

    @Select(" SELECT * FROM answer limit #{offSet},#{limit} ")
    List<Answer> selectByLimit(@Param("offSet") int offSet, @Param("limit") int limit);

    @Select(" SELECT * FROM answer")
    List<Answer> selectList();


    @Update(" update answer set answer_id = #{answerId} where id = #{id}")
    int update(@Param("id") Integer id,@Param("answerId") Integer answerId);


    @Select(" SELECT * FROM answer where data = #{userName}")
    List<Answer> selectByParams(UserReq req);


    //Provider方式：
//    @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = Integer.class)
    @InsertProvider(type = AnswerProvider.class, method = "insertProvider")
    int insertProvider(Answer answer);

    @SelectProvider(type = AnswerProvider.class, method = "selectBySelfProvider")
    List<CommonDTO> selectBySelfProvider(JSONObject jsonObject);


    /**
     * Provider类，sql实例
     */
    class AnswerProvider {

        public String insertProvider(Answer answer) {
            SQL sql = new SQL();
            sql.INSERT_INTO("answer");
            if (answer.getAnswerId() != null) {
                sql.VALUES("answer_id", "#{answerId}");
            }
            if (StringUtils.isNotBlank(answer.getData())) {
                sql.VALUES("data", "#{data}");
            }

            return sql.toString();
        }

        public String selectBySelfProvider(JSONObject jsonObject) {
            StringBuffer sql = new StringBuffer();
            sql.append("select answer_id as id, data as name from answer");
            if (jsonObject.getInteger("productId") != null) {
                sql.append(" where id = #{productId}");
            }
            return sql.toString();
        }


    }


}
